//
//  TDSearchCarController.m
//  TBRentClient
//
//  Created by tonbright on 2018/6/5.
//  Copyright © 2018年 tonbright. All rights reserved.
//
static NSString *filePath = @"kSearchCarHistory";
#import "TDSearchCarController.h"
#import "TDHistorySearchCellCell.h"
#import "TDSearchCarCell.h"

#import "TDCarSourceListC.h"
#import "TDSearchStoreC.h"
#import "TDChooseCarC.h"
#import "TDCarDetailC.h"
#import <IQKeyboardManager.h>
#import "NetWorkRequest.h"
#import "UIView+ZLExtension.h"

#import "LocationHelper.h"

@interface TDSearchCarController ()<UITableViewDelegate, UITableViewDataSource,TDHistorySearchCellCellDelegate,UITextFieldDelegate,ISGLocationHelperDelegate>
@property (nonatomic, strong) UITableView      *tableView;
@property (nonatomic,copy)NSString *searchStr;//搜索字符串-----
@property (nonatomic,strong)NSArray *searchArray;//搜索数组-----
@property (weak, nonatomic) IBOutlet UIView *view_search;
@property (nonatomic,strong)NSArray *historyTitleArray;//历史存储数组
@property (weak, nonatomic) IBOutlet UITextField *tf_searchStr;

@property (nonatomic, strong) LocationHelper   *locationHelper;

@property (nonatomic,strong)ISGLocationInfoModel *locationModel;

@end

@implementation TDSearchCarController

- (void)viewDidLoad {
    [super viewDidLoad];
    _searchStr = @"";
     [_tf_searchStr addTarget:self action:@selector(searchStrChange:) forControlEvents:UIControlEventEditingChanged];
//    [_tf_searchStr addDoneOnKeyboardWithTarget:self action:@selector(doneBtnClick)];
    _tf_searchStr.delegate = self;
    _tf_searchStr.returnKeyType = UIReturnKeySearch;
    [self loadData];
    [self setupUI];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
}

- (void)setupUI {
    //添加tableView
    self.view.backgroundColor = [UIColor whiteColor];
    [self setupTableView];
}


- (void)startLocation {
    _locationHelper = [[LocationHelper alloc] init];
    _locationHelper.delegate = self;
    [_locationHelper startLocation];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
    if (_isPush) {
        [self startLocation];
    }
}


#pragma mark -ISGLocationHelperDelegate
- (void)locationHelper:(LocationHelper *)helper successWithModel:(ISGLocationInfoModel *)model {
    _locationModel = model;
    [_locationHelper stopLocation];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [IQKeyboardManager sharedManager].enableAutoToolbar = YES;
}

- (void)searchStrChange:(UITextField *)tf {
    self.searchStr = tf.text;
    if ([HelpObject isBlankString:self.searchStr]) {
        [self.tableView reloadData];
        return;
    }
    //发起网络搜索
    [self loadNetData];
}

- (void)setupTableView {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.bottom.offset(0);
        make.top.equalTo(self.view_search.bottom).offset(1);
    }];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableFooterView = [UIView new];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.showsVerticalScrollIndicator = NO;
    [self.tableView registerNib:[UINib nibWithNibName:@"TDHistorySearchCellCell" bundle:nil] forCellReuseIdentifier:@"TDHistorySearchCellCellId"];
    [self.tableView registerNib:[UINib nibWithNibName:@"TDSearchCarCell" bundle:nil] forCellReuseIdentifier:@"TDSearchCarCellId"];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 50;
    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
}

- (IBAction)closeBtnClick:(UIButton *)sender {
    [self.view endEditing:YES];
    [self dismissViewControllerAnimated:YES completion:nil];
}



- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self.tf_searchStr becomeFirstResponder];
}


#pragma mark - 实现数据源方法
#pragma mark - 返回组
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

#pragma mark - 返回行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [HelpObject isBlankString:_searchStr] ?  1 : _searchArray.count;
}

#pragma mark - 返回每行内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([HelpObject isBlankString:_searchStr]) {
        //自定义cell
        TDHistorySearchCellCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TDHistorySearchCellCellId" forIndexPath:indexPath];
        cell.delegate = self;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        if ([HelpObject isBlankString:self.searchStr]) {
            cell.titleArray = _historyTitleArray;
            //取出历史数据赋值------
            //        model = self.suggestSearchArray[indexPath.row];
        }else {
            //        model = self.searchArray[indexPath.row];
        }
        //返回
        return cell;
    }
    TDSearchCarCell *searchCarCell = [tableView dequeueReusableCellWithIdentifier:@"TDSearchCarCellId" forIndexPath:indexPath];
    if (indexPath.row < _searchArray.count) {
        searchCarCell.lbe_search.text = _searchArray[indexPath.row];
    }
    return searchCarCell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [HelpObject isBlankString:_searchStr] ?  Height -  (_view_search.zl_y + _view_search.zl_height) : 50;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
//    TDSearchStoreC *searchStoreC = [[TDSearchStoreC alloc] init];
//    [self.navigationController pushViewController:searchStoreC animated:YES];
    [self.view endEditing:YES];
    if (![HelpObject isBlankString:_searchStr]) {
        NSString *title = self.searchArray[indexPath.row];
        
        NSMutableArray *tmpHistoryList = [HelpObject getDocumentDicStrPath:filePath];
        //取出当前用户的历史数据------------------------------
        //        NSMutableArray *tmpPoiList = [dic objectForKey:@"dingxiaolong"];
        if (!tmpHistoryList) {
            tmpHistoryList = [NSMutableArray array];
        }
        [tmpHistoryList enumerateObjectsUsingBlock:^(NSString *historyStr, NSUInteger idx, BOOL * _Nonnull stop) {
            //删除历史存在的相同数据-------
            if ([historyStr isEqualToString:title]) {
                [tmpHistoryList removeObject:historyStr];
            }
        }];
        [tmpHistoryList insertObject:title atIndex:0];//存储当前账户的数据-------
        [HelpObject writeToDocument:tmpHistoryList strPath:filePath];
        
        [tableView deselectRowAtIndexPath:indexPath animated:NO];
        if (_isPush) {
            if (!_locationModel || [HelpObject isBlankString:_locationModel.longitude]) {
                self.noticeText = @"定位失败,无法获取附近门店,请稍后重试";
                return;
            }
            TDCarSourceListC *carSourceListC = [[TDCarSourceListC alloc] init];
            carSourceListC.locationModel = self.locationModel;
            carSourceListC.historyStr = title;
            [self.navigationController pushViewController:carSourceListC animated:YES];
        }else {
            if (self.searchCarCBlock) {
                self.searchCarCBlock(title);
            }
            [self dismissViewControllerAnimated:YES completion:nil];
        }
        
    }
    
}

// MARK: - 历史记录清除按钮cell点击事件------
- (void)historySearchCellCleanBtnClick {
    NSMutableArray *tmpHistoryList = [HelpObject getDocumentDicStrPath:filePath];
    tmpHistoryList = [NSMutableArray array];
    [HelpObject writeToDocument:tmpHistoryList strPath:filePath];
    self.historyTitleArray = tmpHistoryList;
    [self.tableView reloadData];
}

// MARK: - 历史按钮点击事件-----------
- (void)historySearchCellSearchStrBtnClick:(NSString *)historyStr {
    [self.view endEditing:YES];
    if (_isPush) {
        if (!_locationModel || [HelpObject isBlankString:_locationModel.longitude]) {
            self.noticeText = @"定位失败,无法获取附近门店,请稍后重试";
            return;
        }
        TDCarSourceListC *carSourceListC = [[TDCarSourceListC alloc] init];
        carSourceListC.locationModel = self.locationModel;
        carSourceListC.historyStr = historyStr;
        [self.navigationController pushViewController:carSourceListC animated:YES];
    }else {
        if (self.searchCarCBlock) {
            self.searchCarCBlock(historyStr);
        }
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}


- (void)doneBtnClick {
    [self jump2carSourceC];
}

// MARK: - 搜索按钮点击事件-----------------
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self jump2carSourceC];
    return YES;
}

- (void)jump2carSourceC {
    if (![HelpObject isBlankString:_tf_searchStr.text]) {
        NSMutableArray *tmpHistoryList = [HelpObject getDocumentDicStrPath:filePath];
        //取出当前用户的历史数据------------------------------
        //        NSMutableArray *tmpPoiList = [dic objectForKey:@"dingxiaolong"];
        if (!tmpHistoryList) {
            tmpHistoryList = [NSMutableArray array];
        }
        __weak typeof(self) weakSelf = self;
        [tmpHistoryList enumerateObjectsUsingBlock:^(NSString *historyStr, NSUInteger idx, BOOL * _Nonnull stop) {
            //删除历史存在的相同数据-------
            if ([historyStr isEqualToString:weakSelf.tf_searchStr.text]) {
                [tmpHistoryList removeObject:historyStr];
            }
        }];
        [tmpHistoryList insertObject:_tf_searchStr.text atIndex:0];//存储当前账户的数据-------
        [HelpObject writeToDocument:tmpHistoryList strPath:filePath];
    }
    [_tf_searchStr resignFirstResponder];
    if (_isPush) {
        if (!_locationModel || [HelpObject isBlankString:_locationModel.longitude]) {
            self.noticeText = @"定位失败,无法获取附近门店,请稍后重试";
            return;
        }
        TDCarSourceListC *carSourceListC = [[TDCarSourceListC alloc] init];
        carSourceListC.locationModel = self.locationModel;
        carSourceListC.historyStr = _tf_searchStr.text;
        [self.navigationController pushViewController:carSourceListC animated:YES];
    }else {
        if (self.searchCarCBlock) {
            self.searchCarCBlock(_tf_searchStr.text);
        }
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

// MARK: - 加载数据
- (void)loadData {
    [self loadLocalData];
    [self loadNetData];
}
// MARK: - 本地数据
- (void)loadLocalData {
    //    self.detailCarModel = [[TDDetailCarModel alloc] init];
    //    _detailCarModel.isShowAllDetailDesc = @"0";
    //取出历史记录
    NSMutableArray *tmpHistoryList = [HelpObject getDocumentDicStrPath:filePath];
    if (!tmpHistoryList) {
        tmpHistoryList = [NSMutableArray array];
    }
    //取出当前用户名的历史信息------或者对应userId的-------存储的数据和当前账号无关了---💔
    self.historyTitleArray = tmpHistoryList;
}

// MARK: - 获取网络数据-----
- (void)loadNetData {
    NSDictionary *parDic = @{@"search":[HelpObject changeNull:_searchStr],
                             };
    __weak typeof(self) weakSelf = self;
    [self progressHUDShowWithText:nil];
    // MARK: - 获取附近位置的网络数据了-----------------------------
    [NetWorkRequest postNetRequestData:CarSearchStrTD parmeters:parDic response:^(NSDictionary *response) {
        [weakSelf progressHUDHideImmediately];
        weakSelf.searchArray = response[@"data"][@"fuzzylist"];
        [weakSelf.tableView reloadData];
    } netError:^(NSError *error) {
        [weakSelf progressHUDHideImmediately];
    }];
}

@end
